import configparser
import json
import os
import webview
from pickle import TRUE
from diskcache import Cache
import lib.config as config

# 配置pywebview关闭提示的中文翻译
import lib.material
from lib import helpers, until, spiderbd_v3
from lib.email import sendEmail
from lib.watchlogs import watchlogs, writeNull

chinese = {
    "global.quitConfirmation": u"确定关闭?",
}

rootPath = config.rootPath
CachePath = os.path.abspath('.') + "//data"
runLogsFilePath = config.logging_path +"/bd_runlogger.log"
# 传给前端的api对象, 定义了一个可以通过js调用退出当前应用的函数
class Api:
    def __init__(self) -> None:
        self._window = None

    def set_window(self, window):
        self._window = window

    def quit(self):
        self._window.destroy()

def init():
    login_directory_path = CachePath + "//login"
    if not os.path.exists(login_directory_path):
        # 如果目录不存在，使用os.makedirs()函数创建多级目录
        os.makedirs(login_directory_path)
    LogoCache = Cache(login_directory_path, 3600 * 3)

    cache_file = os.getcwd() + '/data/bdsetconf.cache'
    if not os.path.exists(cache_file):
        inifile = os.getcwd() + '//bdkpconf.ini'

        if not os.path.exists(inifile):
            bdconf = {
                "search_stay_min_num": 2,
                "search_stay_max_num": 10,
                "depth_max": 10,
                "threads_max_num": 1,
                "memory_min_num": 1024,
                "proxy_url": '',
                "page_load_timeout": 30,
                "proxy_ip_interval": 5
            }
        else:
            iniConfig = configparser.ConfigParser()
            iniConfig.read(inifile)
            bdconf = {
                "search_stay_min_num": iniConfig.get('BD_SETCONF', 'search_stay_min_num') or 1,
                "search_stay_max_num": iniConfig.get('BD_SETCONF', 'search_stay_max_num') or 10,
                "depth_max": iniConfig.get('BD_SETCONF', 'depth_max') or 10,
                "threads_max_num": iniConfig.get('BD_SETCONF', 'threads_max_num') or 1,
                "memory_min_num": iniConfig.get('BD_SETCONF', 'memory_min_num') or 1024,
                "proxy_url": iniConfig.get('BD_SETCONF', 'proxy_url') or '',
                "page_load_timeout": iniConfig.get('BD_SETCONF', 'page_load_timeout') or 30,
                "proxy_ip_interval": iniConfig.get('BD_SETCONF', 'proxy_ip_interval') or 5
            }

        with open(cache_file, 'wb') as f:
            f.write(json.dumps(bdconf).encode('utf-8'))
            



def material_getList():
    getlist = material.Material().getList()
    # jsonList = json.loads(getlimit)
    return getlist

def pymaterial_updateRec(data):
    return material.Material().updateRec(data)

def pymaterial_deleteRec(data):
    return material.Material().delete_id(data)

def pyDelete_all_data():
    return material.Material().delete_all_data()

def pyImportLins_data(data):
    return material.Material().importLins_data(data)

def pyUpdateIsuerRec(data):
    return material.Material().updateIsuerRec(data)

def pyDelete_ids(ids):
    return material.Material().delete_ids(ids)

def pyAddRec(data):
    return material.Material().addRec(data)

def pyWatchdog():
    return watchlogs(runLogsFilePath)

def pyWatchClear():
    return writeNull(runLogsFilePath)

def pyFeedBack(feeback):
    return sendEmail(feeback)

def pyUpdateIsuerAllRec(ids):
    return material.Material().updateIsuerAllRec(ids)

def pybdSetconfCache(opt='r',data=None):
    return helpers.bdSetconfCache(opt, data)

def pyAppcdkeyHandle(opt=''):
    return helpers.get_app_serial(opt)


def pybdStart(loop_option):
    ret = spiderbd_v3.BDkp().sync_main(loop_option)
    return ret

def pyCacheIps(ips='',opt='save'):
    return until.cacheIps(ips,opt)

def pyTestPingStatus(ip):
    return until.TestPingStatus(ip)

if __name__ == "__main__":
    # 实例化Api类
    init()
    api = Api()
    if not hasattr(webview, 'api'):
        window = webview.create_window(
            title='EsonSeo',
            fullscreen=False,  # 以全屏模式启动
            width=1180,  # 自定义窗口大小
            height=800,
            resizable=TRUE,  # 固定窗口大小
            text_select=False,  # 禁止选择文字内容
            confirm_close=True,  # 关闭时提示
            background_color='#000',
            js_api=api,  # 将上面实例化后的Api对象传给前端js调用
            url='http://localhost:5173'
            # url='bd_vue/dist/index.html'
        )
        # --划重点--务必记得需要将上面创建的window对象再通过函数传给实例化后的api对象
        api.set_window(window)
        # 启动程序
        window.expose(material_getList, pymaterial_updateRec,pymaterial_deleteRec,pyDelete_all_data,pyImportLins_data,pyUpdateIsuerRec,pyDelete_ids,pyAddRec,pyWatchdog,pyWatchClear,pyFeedBack,pyUpdateIsuerAllRec,pybdSetconfCache,pybdStart,pyCacheIps,pyTestPingStatus,pyAppcdkeyHandle)  # 允许html 页面里访问test
        webview.start(localization=chinese, debug=True)
        # webview.start(localization=chinese)
    else:
        print("93 >>>>")

